<?php

namespace app\common\service;

use app\common\model\User;
use app\common\model\UserWechat;
use app\common\util\Result;
use app\controller\mobile\ErrorCode;
use EasyWeChat\Kernel\Exceptions\HttpException;
use think\facade\Log;
use app\common\model\Config;
use app\common\util\EnvHelper;
use EasyWeChat\MiniApp\Application;

class WechatXcxService extends Service
{
    protected $application;

    public function __construct(\think\App $app)
    {
        parent::__construct($app);

        $config = Config::getConfigContent('wechat_xcx');
        if (empty($config)) {
            throw $this->exception('微信配置为空，无法使用小程序相关功能');
        }
        $wxconfig = [
            'app_id' => $config->app_id,
            'secret' => $config->app_secret,
            'token' => 'wechat',
            /**
             * 是否使用 Stable Access Token
             * 默认 false
             * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
             * true 使用 false 不使用
             */
            'use_stable_access_token' => true,
            'http' => [
                'retry' => [
                    // 最大重试次数
                    'max_retries' => 3,
                    // 请求间隔 (毫秒)
                    'delay' => 1000,
                ],
                'timeout' => 20.0,
            ],
        ];

        $this->application = new Application($wxconfig);
    }

    public function getPhone($param = [])
    {
        $this->autoParams($param);

        $code = $this->req('code');
        // 从微信api获取手机号
        $response = $this->application->getClient()->postJson('wxa/business/getuserphonenumber', ['code' => $code]);
        Log::info("用户获取手机号：" . print_r($response->toArray(false), true));
        // 检查错误码
        if ($response['errcode'] != 0) {
            Log::alert('获取微信手机号信息失败' . print_r($response->toArray(false), true));
            $errcode = $response['errcode'];
            $errmsg = $response['errmsg'];
            throw $this->exception("获取微信登录信息失败[{$errcode}: {$errmsg}]", 102);
        }

        return $response['phone_info']['phoneNumber'];
    }

    public function code2session($param = []): Result
    {

        $param = $this->autoMergeParams($param);
        $code = getValueFromArray("code", $param);
        $utils = $this->application->getUtils();

        try {
            $response = $utils->codeToSession($code);
        } catch (HttpException $e) {
            return Result::failed(400, $e->getMessage());
        }
        // 检查错误码
        if (!isset($response['openid']) && $response['errcode'] != 0) {
            Log::alert('获取微信登录信息失败' . print_r($response, true));
            $errcode = $response['errcode'];
            $errmsg = $response['errmsg'];
            return Result::failed($errcode, $errmsg, $response);
            //throw $this->exception("获取微信登录信息失败[{$errcode}: {$errmsg}]", 102,$response);
        }
        //如果成功了
        $where = [];
        $where[] = ["openid", "=", getValueFromArray("openid", $response)];
        $model = UserWechat::where($where)->find();
        $hidden = ["session_key", "openid", "delete_time", "update_time", "create_time", "appid"];
        if (!$model) {
            $model = new UserWechat();
            $model->openid = getValueFromArray("openid", $response);;
            $model->session_key = getValueFromArray("session_key", $response);
            $model->unionid = getValueFromArray("unionid", $response);
            $model->save();
            $model->bind_key = md5($model->id . $model->openid);
            //return Result::success($model->hidden($hidden));
        } else {
            $model->session_key = getValueFromArray("session_key", $response);
        }

        $model->save();

        return Result::success($model->hidden($hidden));

//        return $response;
    }

    public function getUnlimit($scene, $page = 'pages/index/index', $env_version = '', $width = 430)
    {
        $envVersion = $env_version ?: match (EnvHelper::getReleaseType()) { // 确认小程序运行环境
            EnvHelper::RELEASE_TYPE_DEV => 'develop',
            EnvHelper::RELEASE_TYPE_TEST => 'trial',
            EnvHelper::RELEASE_TYPE_PROD => 'release',
            default => 'release'
        };
        $response = $this->application->getClient()->post('wxa/getwxacodeunlimit', [
            'json' => [
                'scene' => $scene,
                'page' => 'pages/index/index',
                'env_version' => $envVersion,
                'width' => $width,
                'check_path' => false
            ]
        ]);
        $contentType = $response->getHeaderLine('content-type');
        if (str_contains($contentType, 'application/json')) {
            $error = $response->toArray();
            if ($error['errcode'] != 0) {
                Log::alert('获取微信手机号信息失败' . print_r($error, true));
                $errcode = $error['errcode'];
                $errmsg = $error['errmsg'];
                throw $this->exception("获取微信登录信息失败[{$errcode}: {$errmsg}]", 102);
            }
        }
        $data = $response->getContent();
        return $data;
    }

    /**
     * 解绑 微信号
     * @param User $user
     * @return Result
     */
    public function unbind(User $user = null): Result
    {
        if (!$user) {
            return Result::failed(608, "用户未登录");
        }
        if ($user->user_wechat_id == 0) {
            return Result::failed(608, "用户未绑定微信");
        }
        $user->bind_key = "";
        $user->bind_status = User::BIND_STATUS_DELETE_BIND;
        $user->bind_unpass_info = "";
        $user->user_wechat_id = 0;
        $res = $user->save();
        if ($res === false) {
            return Result::failed(999, "解绑失败");

        }
        return Result::success();
    }

    /**
     * 绑定
     * @param $param
     * @param User $user
     * @return Result
     */
    public function bind($param, User $user): Result
    {
        $param = $this->autoMergeParams($param);
        if ($user->bind_status == User::BIND_STATUS_BIND) {
            return Result::failed(999, "当前账号已被微信绑定，请先解绑");
        }
        $bindKey = getValueFromArray('bind_key', $param);
        $wechatUserId = getValueFromArray('user_wechat_id', $param);
        $whereWechatUser = [];
        $whereWechatUser[] = ["bind_key", "=", $bindKey];
        $whereWechatUser[] = ["id", "=", $wechatUserId];
        $userWechat = UserWechat::where($whereWechatUser)->find();
        if (!$userWechat) {
            return Result::failed(999, "未找到微信用户");
        }
        //查看微信有没有绑定别的账号
        $whereUser = [];
        $whereUser[] = ["user_wechat_id", "=", $wechatUserId];
        $bindUsers = User::where($whereUser)->select();
        $count = count($bindUsers);
        if ($count) {
            $str = "";
            $dot = "";
            foreach ($bindUsers as $key => $value) {
                $str .= $dot . $value["login_name"];
                $dot = "、";
            }
            return Result::failed(999, "该微信已经被[$str]绑定，请更换微信号");
        }
        $user->bind_key = getValueFromArray('bind_key', $param);
        $user->user_wechat_id = getValueFromArray('user_wechat_id', $param);
        if (in_array($user->bind_status, [User::BIND_STATUS_DELETE_BIND, User::BIND_STATUS_UN_PASS])) {
            $user->bind_status = User::BIND_STATUS_AUDIT;
        }
        if ($user->bind_status == User::BIND_STATUS_UNBIND) {
            $user->bind_status = User::BIND_STATUS_BIND;
        }

        $res = $user->save();
        if ($res === false) {
            return Result::failed(999, "绑定失败");

        }
        return Result::success();


    }

    public function checkBind(User $user = null)
    {
        if (!$user) {
            return Result::failed(999, "请先登录");
        }
        //2024年3月29日17:52:17 先暂时去掉
        /*if($user->bind_status == User::BIND_STATUS_UNBIND ){
            return Result::failed(701, "绑定未通过:" . $user->bind_unpass_info);
        }
        if ( $user->bind_status == User::BIND_STATUS_DELETE_BIND) {
            return Result::failed(702, "账号未绑定微信号，请先绑定微信");
        }
        if ($user->bind_status == User::BIND_STATUS_AUDIT) {
            return Result::failed(703, "绑定审核中,请耐心等待，或联系客服协助解决！");
        }
        if ($user->bind_status == User::BIND_STATUS_UN_PASS) {
            $user->bind_key = "";
            $user->user_wechat_id = 0;
            $user->save();//清空绑定信息
            return Result::failed(704, "绑定未通过:" . $user->bind_unpass_info);
        }*/
        return Result::success();
    }


}